import axios from "axios";
import { Message } from "element-ui";
import { getToken } from "./auth";
import config from "@/config";
import store from "../store";
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 60000 // 请求超时时间
});
// request拦截器
service.interceptors.request.use(
  xconfig => {
    console.log(xconfig)
    xconfig.headers["X-Code"] = config.app.name;
    xconfig.credentials = 'same-origin';
    xconfig.withCredentials = true;
    // if (getToken()) {
    //   xconfig.headers["ticket"] = getToken(); // 让每个请求携带自定义ticket 请根据实际情况自行修改
    // }
    if(xconfig.method == "get"){
      xconfig.url = xconfig.url + "?" + json2Form(xconfig.data);
    }
    console.log(xconfig)
    return xconfig;
  },
  error => {
    // Do something with request error
    Message({
      message: "啊哦~请求出错了(ಥ﹏ಥ)",
      type: "error",
      duration: 5 * 1000
    });
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.status !== 200) {
      Message({ message: res.message, type: "error", duration: 5 * 1000 });
      if (res.status === 401) {
        store.dispatch("ClearRoles").then(() => {
          location.href = "#/403";
        });
      }
      return Promise.reject("error");
    } else {
      return response.data;
    }
  },
  error => {
    Message({
      message: "啊哦~请求失败了(ಥ﹏ಥ)",
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}
export default service;
